﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using Booky.Common;

namespace ExportBookmark
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (Request.QueryString["burl"] != null && Request.QueryString["btitle"] != null)
                {
                    bool doesBurlExist = Request.Url.AbsoluteUri.IndexOf("burl=") >= 0 ? true : false;

                    bool doesBtitleExist = Request.Url.AbsoluteUri.IndexOf("btitle=") >= 0 ? true : false;

                    if (doesBurlExist && doesBtitleExist)
                    {
                        //Get burl
                        string burl = Request.QueryString["burl"];

                        //Get btitle
                        string btitle = Request.QueryString["btitle"];

                        //Fancy object
                        BookmarkJson b = new BookmarkJson();
                        b.Url = burl;
                        b.Title = btitle;
                        //To json
                        string url = JsonConvert.SerializeObject(b);

                        string filename = Guid.NewGuid().ToString();

                        filename = filename.Substring(0, 6) + ".booky"; //btitle.Replace(" ", "") + "_" + 
                        
                        //To the file system
                        File.WriteAllText(Globals.BookmarkFileLocation + filename, url);

                        Encryption ec = new Encryption();
                        
                        Response.Redirect("/Handlers/BookyFileHandler.ashx?b=" +  HttpUtility.UrlEncode(ec.Encrypt(filename)));
                        
                    }
                }
            }
            catch (Exception ex)
            {
                Response.Write("Error: " + ex.ToString() + ex.StackTrace + ex.Source);
            }
        }
    }
}